package net.yebaihe.buildapp.yyh;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class ChooseFiles extends Activity implements AdaptSelChangeNotify {
    private String baseDir="";
	ArrayList<File> fileValueList=new ArrayList<File>();
	private int rowidx;
	private String mode;

    class FileSimpleAdapter extends SimpleAdapter {

    	private LayoutInflater mInflater;
    	private List<? extends Map<String, ?>> mData;
    	private int mResource;
    	protected long totalSize=0;
    	private AdaptSelChangeNotify mNotify;

    	public FileSimpleAdapter(Context context,
    			List<? extends Map<String, ?>> data, int resource, String[] from,
    			int[] to) {
    		super(context, data, resource, from, to);
    		mData = data;
    		mResource = resource;
    		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	}
    	
    	public View getView(int position, View convertView, ViewGroup parent) {
            return createViewFromResource(position, convertView, parent, mResource);
        }
    	
    	private View createViewFromResource(int position, View convertView,
                ViewGroup parent, int resource) {
            View v;
            if (convertView == null) {
                v = mInflater.inflate(resource, parent, false);
            } else {
                v = convertView;
            }

            bindView(position, v);

            return v;
        }
    	
    	private void bindView(int position, View view) {
            final Map map = mData.get(position);
            if (map == null) {
                return;
            }
    		File f=(File) map.get("file");
    		TextView v=(TextView) view.findViewById(R.id.nametitle);
    		v.setText(f.getName());
    		
    		ImageView i=(ImageView)view.findViewById(R.id.idicon);
    		
    		CheckBox c=(CheckBox) view.findViewById(R.id.idcheckbox);
    		if (f.isDirectory()){
    			c.setVisibility(View.INVISIBLE);
    			i.setImageResource(R.drawable.folder);
    			c.setTag(f.getAbsoluteFile());
    			return;
    		}
    		else{
    			c.setVisibility(View.VISIBLE);
    			i.setImageResource(R.drawable.file);
    		}
    		c.setTag(f.getAbsoluteFile());
    		int idx=fileValueList.indexOf(f);
    		c.setChecked(idx>=0);
    		if (mode.equals("single")){
    			c.setVisibility(View.GONE);
    		}
    		
    		c.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    			@Override
    			public void onCheckedChanged(CompoundButton buttonView,
    					boolean isChecked) {
    				File info=(File) buttonView.getTag();
    				if (isChecked){
    					int idx=fileValueList.indexOf(info);
    					if (idx<0){
    					fileValueList.add(info);
    					totalSize+=info.length();
    					}
    				}
    				else{
    					int idx=fileValueList.indexOf(info);
    					if (idx>=0){
    						fileValueList.remove(idx);
    						totalSize-=info.length();
    					}
    				}
    				if (mNotify!=null){
    					mNotify.onAdapeSelectionChange("");
    				}
    			}
    		});
    		
    	}
    	public void setOnSelectChange(AdaptSelChangeNotify notify) {
    		mNotify=notify;
    	}
    	
    }
    
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.filelist);
        baseDir=getIntent().getStringExtra("base");
        rowidx=getIntent().getIntExtra("index", -1000);
        mode=getIntent().getStringExtra("mode");
        
        ListView filelistview = (ListView) findViewById(R.id.filelist);
        filelistview.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int arg2,
					long arg3) {
				CheckBox c=(CheckBox) view.findViewById(R.id.idcheckbox);
				File info=(File) c.getTag();
				if (info.isDirectory()){
					TextView v=(TextView) view.findViewById(R.id.nametitle);
					//Toast.makeText(main.this, v.getText(), Toast.LENGTH_LONG).show();
					baseDir+="/"+v.getText();
					refreshFileList();
				}
				else{
					if (mode.equals("single")){
						Intent intent=new Intent();
						String ret=info.getAbsolutePath();
						intent.putExtra("files", ret);
						intent.putExtra("index", rowidx);
						setResult(RESULT_OK, intent);
						finish();
					}
				}
			}
        });
        
        Button b=(Button) this.findViewById(R.id.idfinish);
        b.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent=new Intent();
				String ret="";
				for (int i=0;i<fileValueList.size();i++){
					ret+=fileValueList.get(i).getAbsolutePath()+";";
				}
				intent.putExtra("files", ret);
				intent.putExtra("index", rowidx);
				setResult(RESULT_OK, intent);
				finish();
			}
        });
        if (mode.equals("single")){
        	b.setVisibility(View.GONE);
        }
        
        refreshFileList();
    }

	private List<Map<String, Object>> getFiles() {
		File base=new File(baseDir);
		Log.d("myown", baseDir);
		List<Map<String, Object>> contents=new ArrayList<Map<String, Object>>();
		File[] files = base.listFiles();
		if (files==null) return contents;
		for (int i=0;i<files.length;i++){
			File f=files[i];
			if (f.isDirectory()){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("name", f.getPath());
				map.put("file", f);
				contents.add(map);
			}
		}
		//再增加文件
		for (int i=0;i<files.length;i++){
			File f=files[i];
			if (!f.isDirectory()){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("name", f.getPath());
				map.put("file", f);
				contents.add(map);
			}
		}
		return contents;
	}
        
	private void refreshFileList() {
		FileSimpleAdapter fileadapter = new FileSimpleAdapter(this,
				(List<Map<String, Object>>) getFiles(), R.layout.filerow,
				new String[] {}, new int[] {});
		ListView filelistview=(ListView) this.findViewById(R.id.filelist);
		fileadapter.setOnSelectChange(this);
		filelistview.setAdapter(fileadapter);
	}

	@Override
	public void onBackPressed() {
		String up=upDir(baseDir);
		if (!up.equals(baseDir)){
			baseDir=up;
			refreshFileList();
			return;
		}
		finish();
	}	

	private String upDir(String base) {
		int idx=base.lastIndexOf("/");
		if (idx>0){
			base=base.substring(0,idx);
			if (base.length()<Environment.getExternalStorageDirectory().getAbsolutePath().length()){
				base=Environment.getExternalStorageDirectory().getAbsolutePath();
			}
		}
		return base;
	}

	
	@Override
	public void onAdapeSelectionChange(String string) {
		// TODO Auto-generated method stub
		
	}

}
